package com.nondo.rdp.finance.service.impl.course;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.Section;
import com.nondo.rdp.finance.domain.course.SectionComment;
import com.nondo.rdp.finance.domain.course.SectionProcess;
import com.nondo.rdp.finance.model.course.SectionBean;
import com.nondo.rdp.finance.model.course.SectionCommentBean;
import com.nondo.rdp.finance.repository.course.CourseRepository;
import com.nondo.rdp.finance.repository.course.SectionCommentRepository;
import com.nondo.rdp.finance.repository.course.SectionRepository;
import com.nondo.rdp.finance.service.course.CourseService;
import com.nondo.rdp.finance.service.course.SectionProcessService;
import com.nondo.rdp.finance.service.course.SectionService;

@Transactional
@Service
public class SectionServiceImpl implements SectionService {
	
	 @Autowired
	 CourseService courseService;
	
    @Autowired
    CourseRepository courseRepository;

    @Autowired
    SectionRepository sectionRepository;
    
    @Autowired
   	SectionProcessService sectionProcessService;

    @Autowired
    SectionCommentRepository sectionCommentRepository;
    
    @Override
    public Section findOne(Long id) {
        return this.sectionRepository.findOne(id);
    }

    @Override
    public Section save(Section section) {
        return this.sectionRepository.save(section);
    }
    
    

    @Override
    public void update(Section section) {
        this.sectionRepository.save(section);
    }

    @Override
    public void delete(Long id) {
        this.sectionRepository.deleteById(id);
    }

    @Override
    public Page<Section> findAll(Page<Section> page, Section section) {
        Sort sort = null;
		if ("ASC".equals(section.getOrderBy())) {
			sort = new Sort(Sort.Direction.ASC, "sortNum").and(new Sort(Sort.Direction.ASC, "createDate"));
		} else {
			sort = new Sort(Sort.Direction.DESC, "sortNum").and(new Sort(Sort.Direction.DESC, "createDate"));
		}
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Section> dictPage = sectionRepository.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (section != null) {
                if (section.getType() != null) {
                    predicates.add(builder.equal(root.get("type"), section.getType()));
                }
                if (StringUtils.isNotEmpty(section.getName())) {
                    predicates.add(builder.like(root.get("name"), "%" + section.getName() + "%"));
                }
                if (section.getCourseId() != null) {
                    predicates.add(builder.equal(root.get("course").get("id"), section.getCourseId()));
                }
                if (section.getPublisher() != null) {
                    predicates.add(builder.equal(root.get("publisher").get("id"), section.getPublisher().getId()));
                }
            }
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);

            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Section>(dictPage);
    }

    @Override
    public SectionBean getSectionDetail(Section section) {
        SectionBean sq = new SectionBean();

        BeanUtils.copy(section, sq);

        List<SectionComment> comments = sectionCommentRepository.getCommentListBySid(section.getId());
        List<SectionCommentBean> commentBeans = SectionCommentBean.covert2BeanList(comments);

        sq.setComments(commentBeans);
        sq.setCommentNum(commentBeans.size());

        return sq;
    }

    @Override
    public Long getCourseId(Long sectionId) {
        return sectionRepository.getCourseId(sectionId);
    }

    @Override
    public Section findByAlbumIdAndTrackId(int albumId, int trackId) {
        return this.sectionRepository.findByAlbumIdAndTrackId(albumId, trackId);
    }

	@Override
	public List<Section> findByCourseId(Long courseId) {
		return this.sectionRepository.findByCourseId(courseId);
	}
	
	@Override
    public void updateAdmin(Section section) {
        Course course = section.getCourse();
        course.setStatus(0);
        course.setAuditStatus(0);
        this.courseRepository.save(course);
        this.sectionRepository.save(section);
    }

	@Override
	public void updateApp(Section section, User user) {
		SectionProcess sectionProcess = null;
		// 更新课程进度信息
		sectionProcess = this.sectionProcessService.getOne(section.getId(), user.getId());
		if (sectionProcess == null) {
			sectionProcess = new SectionProcess();
			sectionProcess.setSection(section);
			sectionProcess.setUser(user);
			sectionProcess.setPlayState(1);
		}
		this.sectionProcessService.save(sectionProcess);
		 // 更新课程信息
        Course course = section.getCourse();
		course.setReadNum(course.getReadNum() + 1);
		this.courseService.update(course);
		
	}
}